﻿using Pay.Core;
using Pay.Data;
using Pay.DTO;
using Pay.IService;
using Pay.TO;
using System;
using System.Linq;

namespace Pay.Service.Service {
    public class MerchantReceivablesService : ServiceBase, IMerchantReceivablesService, IDisposable {
        private IUnitOfWork _iUnitOfWork;
        private IMarketingPromoterService _iMarketingPromoterService;
        private IMarketingCommonService _iMarketingCommonService;
        private IMerchantService _merchantService;
        public MerchantReceivablesService(IUnitOfWork iUnitOfWork, IMarketingPromoterService iMarketingPromoterService, IMarketingCommonService iMarketingCommonService,
            IMerchantService merchantService) : base(iUnitOfWork) {
            this._iUnitOfWork = iUnitOfWork;
            _iMarketingPromoterService = iMarketingPromoterService;
            _iMarketingCommonService = iMarketingCommonService;
            _merchantService = merchantService;
        }

        /// <summary>
        /// 获取用户账号基本信息
        /// </summary>
        /// <param name="merchantId"></param>
        /// <returns></returns>
        public marketing_user_info_dto GetMarketingUserInfo(long merchantId) {
            var result = new marketing_user_info_dto();
            var user = _merchantService.Get(merchantId);
            result.user_type = user.usertype;

            var authInfo = _merchantService.GetAuth(user.id); ;
            if (authInfo != null) {
                result.real_name = authInfo.account_name;
                result.id_card = authInfo.id_card;
            }

            result.register_time = user.create_time;

            //var tokenUpGrade = context.TokenUpGrade.Where(o => o.ApplyMerchantId == merchantId && o.EUpGradeAudit == EUpGradeAudit.Audited).OrderByDescending(o => o.ApplyTime)
            //                    .FirstOrDefault().ToDtoObject<token_up_grade_dto>();
            var parentMerchant = _merchantService.Get(user.parent_id);

            if (parentMerchant != null) {
                result.inviter_phone = parentMerchant.mobile;
                var parentAuthInfo = _merchantService.GetAuth(parentMerchant.id); //context.AuthInfos.Where(o => o.MerchantId == parentMerchant.id && o.Status == CertifyStatus.Auth).FirstOrDefault();
                if (parentAuthInfo != null) {
                    result.inviter = parentAuthInfo.account_name;
                }
            } else {
                var defaultMerchant = _merchantService.Get(t_RequestMethod.TOKEN_MARKETING_DEFAULT_MEARCHANTNO);
                if (defaultMerchant != null) {
                    result.inviter = defaultMerchant.name;
                    var defaultMerchantReceivables = context.MerchantReceivables.Where(o => o.MerchantId == defaultMerchant.id).FirstOrDefault();
                    if (defaultMerchantReceivables != null) {
                        result.inviter_phone = defaultMerchantReceivables.Mobile;
                    }
                }
            }

            var promoter_info = _iMarketingPromoterService.GetMyPromoterInfo(merchantId);
            if (promoter_info != null) {
                result.direct_num = promoter_info.direct_promoter_num;
                result.indirect_num = promoter_info.indirect_promoter_num;
            }


            return result;
        }
        /// <summary>
        /// 获取收款信息
        /// </summary>
        /// <param name="merchantId"></param>
        /// <returns></returns>
        public merchant_receivables_dto_ex GetReceivables(long merchantId) {
            var dto = context.MerchantReceivables.Where(o => o.MerchantId == merchantId).FirstOrDefault().ToDtoObject<merchant_receivables_dto>();
            if (dto == null) return null;
            var result = new merchant_receivables_dto_ex();
            dto.ToCopyProperty(result);
            result.full_branch_address = dto.region_name + dto.branch_address;
            return result;
        }
        public recivables_dto GetReceivablesInfo(long merchantId) {
            var dto = context.MerchantReceivables.Where(o => o.MerchantId == merchantId).FirstOrDefault().ToDtoObject<recivables_dto>();
            return dto;
        }
        /// <summary>
        /// 获取当前用户公司信息
        /// </summary>
        /// <param name="curMerchantId"></param>
        /// <returns></returns>
        public merchant_receivables_dto_ex GetCurCityCompanyReceivables(long curMerchantId) {
            var cityMerchant = _iMarketingCommonService.GetCityCompanyMerchantByMerchantId(curMerchantId, true);
            return GetReceivables(cityMerchant.id);
        }

        /// <summary>
        /// 更新收款信息
        /// </summary>
        /// <param name="model"></param>
        /// <param name="merchantId"></param>
        /// <returns></returns>
        public bool UpdateReceivables(merchant_receivables_model_ex model, long merchantId) {
            ValidSaveReceivables(model);
            var merchantReceivables = context.MerchantReceivables.Where(o => o.MerchantId == merchantId).FirstOrDefault();
            var createTime = merchantReceivables.CreateTime;
            var dto = merchantReceivables.ToDtoObject<merchant_receivables_dto>();
            model.ToCopyProperty(dto);
            dto.create_time = createTime.ToDateTime();
            dto.update_time = DateTime.Now;
            dto.ToDtoObject(merchantReceivables);
            var region = context.Regions.Where(o => o.Id == dto.region_id).FirstOrDefault();
            if (region != null)
                dto.region_name = region.RegionName;

            return _iUnitOfWork.Commit() > 0;
        }

        private static readonly object objkey = new object();

        /// <summary>
        /// 添加收款信息
        /// </summary>
        /// <param name="model"></param>
        /// <param name="merchantId"></param>
        /// <returns></returns>
        public bool AddReceivables(merchant_receivables_model model, long merchantId) {
            lock (objkey) {
                using (var trans = context.Database.BeginTransaction()) {
                    try {
                        ValidSaveReceivables(model);
                        if (context.MerchantReceivables.Exist(o => o.MerchantId == merchantId))
                            throw new ServerErrorException("您已添加过收款信息");

                        merchant_receivables_dto dto = new merchant_receivables_dto();
                        model.ToCopyProperty(dto);
                        dto.merchant_id = merchantId;
                        dto.create_time = DateTime.Now;
                        dto.update_time = DateTime.Now;
                        var region = context.Regions.Where(o => o.Id == dto.region_id).FirstOrDefault();
                        if (region != null)
                            dto.region_name = region.RegionName;

                        MerchantReceivables merchantReceivables = dto.ToDtoObject<MerchantReceivables>();
                        context.MerchantReceivables.Add(merchantReceivables);
                        _iUnitOfWork.Commit();

                        if (!context.TokenStatistics.Exist(o => o.MerchantId == merchantId)) {//创建用户统计信息
                            TokenStatistics tokenStatistics = new TokenStatistics() { MerchantId = merchantId, CreateTime = DateTime.Now.ToUnix() };
                            context.TokenStatistics.Add(tokenStatistics);
                            _iUnitOfWork.Commit();
                        }

                        trans.Commit();
                        return true;
                    } catch (Exception ex) {
                        trans.Rollback();
                        throw ex;
                    }
                }
            }
        }

        /// <summary>
        /// 保存收款信息验证
        /// </summary>
        /// <param name="model"></param>
        private void ValidSaveReceivables(merchant_receivables_model model) {
            if (string.IsNullOrEmpty(model.mobile))
                throw new ServerErrorException("请输入您的联系电话");
            if (string.IsNullOrEmpty(model.card_no))
                throw new ServerErrorException("请输入您的银行卡号");
            if (string.IsNullOrEmpty(model.account_name))
                throw new ServerErrorException("请输入银行卡户名");
            if (string.IsNullOrEmpty(model.bank_name))
                throw new ServerErrorException("请输入您的银行卡所属银行名称");
            if (string.IsNullOrEmpty(model.branch_name))
                throw new ServerErrorException("请输入您的银行卡开户支行名称");
            if (model.region_id == 0 || !context.Regions.Exist(o => o.Id == model.region_id))
                throw new ServerErrorException("请选择您银行卡开户支行所在地区");
            if (string.IsNullOrEmpty(model.branch_address))
                throw new ServerErrorException("情输入您的银行卡开户支行地址");
        }
    }
}
